using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

using ThinkJot.Core.Blogs;
using ThinkJot.Core.Blogs.Providers;
using ThinkJot.Core.Utils;

public partial class Blogs_ViewReferrersControl : BlogControlBase
{
    DateTime dt;
    ActivityStats stats;

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadDate(); 
        stats = ActivityLog.GetActivityStats(dt, BlogName);
    }

    protected string GetCalendarPopupPath()
    {
        return PathUtility.CombineUrls(SysConfig.ComponentsUrl, "calendarpopup/calendarpopup.js");
    }

    protected string GetDateText()
    {
        return dt.ToString("yyyy/MM/dd");
    }

    protected string GetReferrersHtml()
    {
        List<ActivityStats.ReferrersSummaryItem> referrers = stats.ReferrersSummaryItems;
        
        //remove the ones from the same blog root path
        string blogUrl = GetBlogUrl().ToLower().TrimEnd('/') + "/";
        string mappedBlogUrl = GetMappedBlogUrl().ToLower().TrimEnd('/') + "/";
        referrers.RemoveAll(delegate(ActivityStats.ReferrersSummaryItem item)
        {
            if (item.ReferringUrl.ToLower().StartsWith(blogUrl))
            {
                string stripped = item.ReferringUrl.Substring(blogUrl.Length);
                if (!stripped.Contains("/"))
                    return true;
            }
            if (item.ReferringUrl.ToLower().StartsWith(mappedBlogUrl))
            {
                string stripped = item.ReferringUrl.Substring(mappedBlogUrl.Length);
                if (!stripped.Contains("/"))
                    return true;
            }
            return false;
        });

        string html = "<div class=\"activityStatsItem\"><table>";
        foreach (ActivityStats.ReferrersSummaryItem item in referrers)
        {
            string referringUrl = item.ReferringUrl;
            if (string.IsNullOrEmpty(referringUrl.Trim()))
                referringUrl = "Unknown";
            html += "<tr>";
            html += "<td class=\"activityStatsCol\">" + item.Count + "</td>";
            html += "<td class=\"activityStatsCol\"><a href=\"" + HttpUtility.HtmlEncode(item.ReferringUrl) + "\">" + HttpUtility.HtmlEncode(referringUrl) + "</a></td>";
            html += "</tr>";
        }
        html += "</table></div>";
        return html;
    }

    protected void refreshButton_Click(object sender, EventArgs e)
    {
        //This does nothing ;) -- just posts back
    }

    private void LoadDate()
    {
        string strDate = Request["dateBox"];
        dt = DateTimeUtility.GetDateFromShortDateString(strDate);
    }
}
